package com.guotd.jspwork2.utils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBCUtil {
    private static final String url = "jdbc:hsqldb:hsql://localhost/db";
    private static final String dbUser = "SA";
    private static final String dbPassword = "";
    private static final String DRIVER = "org.hsqldb.jdbc.JDBCDriver";

    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection con = null;
        try {
            con = DriverManager.getConnection(url, dbUser, dbPassword);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    public static int update(String sql, Object[] args) {
        int row = -1;
        try {
            try (Connection con = getConnection()) {
                PreparedStatement pstmt = con.prepareStatement(sql);
                for (int i = 0; i < args.length; i++) {
                    pstmt.setString(i + 1, args[i].toString());}
                row = pstmt.executeUpdate();}
        } catch (Exception ex)
        {
            throw new RuntimeException(ex);
        }
        return row;
    }

    public static List<Object[]> query(String sql, Object[] args, String[] colNames) {
        List<Object[]> res = new ArrayList<>();
        try {
            try (Connection con = getConnection()) {
                PreparedStatement pstmt = con.prepareStatement(sql);
                for (int i = 0; i < args.length; i++) {
                    pstmt.setString(i + 1, args[i].toString());}
                try (ResultSet rs = pstmt.executeQuery()) {
                    while (rs.next()) {
                        Object[] row = new String[colNames.length];
                        for (int i = 0; i < colNames.length; i++) {
                            row[i] = rs.getString(colNames[i]);}
                        res.add(row);}
                }
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);}
        return res;}
}
